package com.sa35.fbs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.sa35.fbs.vo.UserVO;

public class FBSFilter implements Filter {
	private FilterConfig filterConfig;
	private static final String FILTERED_REQUEST = "@@session_context_filtered_request";
	private static final String[] INHERENT_ESCAPE_URIS = { "/login", "/logout","/resources" };

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		if (request != null && request.getAttribute(FILTERED_REQUEST) != null) {
			chain.doFilter(request, response);
		} else {
			request.setAttribute(FILTERED_REQUEST, Boolean.TRUE);
			HttpServletRequest httpRequest = (HttpServletRequest) request;
			UserVO userContext = (UserVO) httpRequest.getSession()
					.getAttribute("fbs_user");

			if (userContext == null
					&& !isURILogin(httpRequest.getRequestURI(), httpRequest)) {
				System.out.println(httpRequest.getRequestURI());
//				String toUrl = httpRequest.getRequestURL().toString();
//				if (!(httpRequest.getQueryString().isEmpty())) {
//					toUrl += "?" + httpRequest.getQueryString();
//				}
//
//				httpRequest.getSession().setAttribute("LOGIN_TO_URL", toUrl);

				request.getRequestDispatcher("/login").forward(request,
						response);
				return;
			}
			chain.doFilter(request, response);
		}
	}

	private boolean isURILogin(String requestURI, HttpServletRequest request) {
		if (request.getContextPath().equalsIgnoreCase(requestURI)
				|| (request.getContextPath() + "/")
						.equalsIgnoreCase(requestURI))
			return true;
		for (String uri : INHERENT_ESCAPE_URIS) {
			if (requestURI != null && requestURI.indexOf(uri) >= 0) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@Override
	public void destroy() {
		this.filterConfig = null;
	}
}